<template>
    <div class="movie-page">
        <router-link to="/movie" class="back-button">返回电影列表</router-link>
        <h1 v-if="movieInfo" class="movie-title" style="word-wrap: break-word; overflow-wrap: break-word;">
            {{ movieInfo.title }}
        </h1>
        <p v-if="movieInfo" class="movie-meta">
            上架时间: {{ movieInfo.addedTime || '未知' }} | 主演: {{ movieInfo.actors || '未知' }} | 评分: {{ movieInfo.score ||
                '未知' }}
            <hr>
            <span class="multi-line-ellipsis">电影描述: {{ movieInfo.desc || '未知' }}</span>
            <hr>
            <!-- 移除 single-line-ellipsis 类，确保图片完整显示 -->
            <span>剧照: 
                <img 
                    :src="movieInfo.picPaths" 
                    alt="剧照" 
                    class="movie-poster" 
                    @error="handleImageError"
                    @load="onImageLoaded"
                    @loadstart="onImageLoadStart"
                />
            </span>
            <hr>
            <span class="single-line-ellipsis">播放地址: <a :href="movieInfo.playUrl" target="_blank">{{ movieInfo.playUrl }}</a></span>
            <hr>
            上传用户id: {{ movieInfo.userid }}
        </p>
        <div v-if="isLogin" class="movie-form-container">
            <h2 class="comment-title">发表评论</h2>
            <div id="editor-container">
                <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
                <Editor v-model="replyContent" :defaultConfig="editorConfig" mode="default"
                    @onCreated="handleCreated" />
            </div>
            <button type="button" class="submit-button" @click="addReply">提交</button>
        </div>
        <div v-if="comments.length > 0" class="movie-list">
            <h2 class="comment-title">评论列表</h2>
            <div v-for="comment in comments" :key="comment.id" class="movie-item">
                <p class="comment-body" style="word-wrap: break-word; overflow-wrap: break-word;">{{ comment.body }}</p>
                <p class="comment-meta">评论时间: {{ comment.addedTime || '未知' }}</p>
                <p class="comment-meta">用户id: {{ comment.userid }}</p>
            </div>
        </div>
        <div v-else class="no-comments">暂无评论</div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, shallowRef } from 'vue';
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { getSingle, add, getList, TableName } from '../utils/request';
import { useRoute } from 'vue-router';
import { useUserStore } from '../stores/user';
import { ElMessageBox } from 'element-plus';

const userStore = useUserStore();
const isLogin = ref(userStore.isAuthenticated);
const user = ref(userStore.getUser);
const editorRef = shallowRef();
const imageLoaded = ref(false);

// 工具栏配置
const toolbarConfig = reactive({
    excludeKeys: [
        'blockquote',
        'headerSelect',
        'color',
        'bgColor',
        'fontSize',
        'fontFamily',
        'lineHeight',
        '|',
        'group-more-style',
        'group-indent',
        'emotion',
        'bulletedList',
        'numberedList',
        'divider',
        'todo',
    ],
});

const comments = ref<any[]>([]);
const route = useRoute();
interface Movie {
    title?: string;
    addedTime?: string;
    picPaths?: string;
    desc?: string;
    actors?: string;
    score?: string;
    userid?: string;
    playUrl?: string;
}
const movieInfo = ref<Movie | null>(null);
const replyContent = ref<string>('');

const editorConfig = {
    placeholder: '请输入评论内容...',
    MENU_CONF: {
        uploadImage: {
            server: '/api/demo/image',
            maxFileSize: 10 * 1024 * 1024,
            onFailed: (file: File, res: any) => {
                console.log(`${file.name} 上传图片失败`, res);
            },
            onError: (file: File, err: Error, res: any) => {
                const showSize = getShortSizeStr(10 * 1024 * 1024);
                ElMessageBox.alert('上传图片失败,最大不能超过' + showSize);
                console.log(`${file.name} 上传图片出错`, err, res);
            },
        },
        uploadVideo: {
            server: '/api/demo/video',
            maxFileSize: 50 * 1024 * 1024,
            onFailed: (file: File, res: any) => {
                console.log(`${file.name} 上传视频失败`, res);
            },
            onError: (file: File, err: Error, res: any) => {
                const showSize = getShortSizeStr(50 * 1024 * 1024);
                ElMessageBox.alert('上传视频失败,最大不能超过' + showSize);
                console.log(`${file.name} 上传视频出错`, err, res);
            },
        },
    },
};

function getShortSizeStr(realSize: number, fixedLength = 0) {
    let showSize = '';
    if (realSize < 1024 * 1024) {
        showSize = (realSize / 1024).toFixed(fixedLength) + 'KB';
    } else {
        showSize = (realSize / (1024 * 1024)).toFixed(fixedLength) + 'MB';
    }
    return showSize;
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

const handleCreated = (editor: any) => {
    editorRef.value = editor;
};

// 图片开始加载
const onImageLoadStart = (event: Event) => {
  console.log('图片开始加载:', (event.target as HTMLImageElement).src);
};

// 图片加载完成
const onImageLoaded = () => {
  imageLoaded.value = true;
};

onMounted(async () => {
    try {
        const idStr = typeof route.query.id === 'string' ? route.query.id : undefined;
        const id = idStr ? parseInt(idStr) : undefined;
        if (id) {
            const res = await getSingle(id.toString(), TableName.Movies);
            movieInfo.value = res;
            comments.value = await getList(TableName.Comments, id, '电影');
        } else {
            console.error('电影 ID 无效');
        }
    } catch (error) {
        console.error('获取电影详情失败:', error);
    }
});

const addReply = async () => {
    if (user.value && user.value.id) {
        if (!replyContent.value) {
            ElMessageBox.alert('评论内容不能为空', '提示');
            return;
        }
        const idStr = typeof route.query.id === 'string' ? route.query.id : undefined;
        const id = idStr ? parseInt(idStr) : undefined;
        if (id) {
            await add({
                articleid: id.toString(),
                body: replyContent.value,
                userid: user.value.id,
                replyType: '电影',
                typeIndex: TableName.Comments
            });
            replyContent.value = '';
            comments.value = await getList(TableName.Comments, id, '电影');
        } else {
            console.error('电影 ID 无效');
        }
    } else {
        ElMessageBox.alert('请先登录', '提示');
    }
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  console.error('图片加载失败:', (event.target as HTMLImageElement).src);
  (event.target as HTMLImageElement).src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="150" height="200"><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="red">图片加载失败</text></svg>';
};
</script>

<style scoped>
.movie-page {
    width: 100%;
    margin: 0 auto;
    padding: 20px;
    margin-top: -70px;
}

.back-button {
    display: inline-block;
    margin-bottom: 20px;
    background-color: #28a745;
    color: white;
    padding: 10px 20px;
    border-radius: 4px;
    text-decoration: none;
    transition: background-color 0.3s;
}

.back-button:hover {
    background-color: #218838;
}

.movie-title {
    font-size: 32px;
    text-align: center;
    margin-bottom: 20px;
}

.movie-meta {
    font-size: 14px;
    color: #666;
    margin-bottom: 20px;
}

.movie-form-container {
    background-color: #f9f9f9;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

#editor-container {
    width: 100%;
    height: auto;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin-bottom: 10px;
}

.submit-button {
    width: 100%;
    background-color: #28a745;
    color: white;
    padding: 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.submit-button:hover {
    background-color: #218838;
}

.movie-list {
    background-color: #f9f9f9;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
}

.movie-item {
    border-bottom: 1px solid #e0e0e0;
    padding-bottom: 10px;
    margin-bottom: 10px;
}

.comment-body {
    line-height: 1.6;
    font-size: 16px;
    margin-bottom: 5px;
}

.comment-meta {
    font-size: 14px;
    color: #666;
}

.no-comments {
    font-size: 16px;
    color: #666;
    text-align: center;
}

hr {
    border: 1px dashed;
    width: 100%;
    margin: 10px 0;
}

.multi-line-ellipsis {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 6;
    overflow: hidden;
    text-overflow: ellipsis;
}

.movie-poster {
    width: 150px;
    height: auto;
    border-radius: 4px;
    transition: opacity 0.3s;
}
</style>